package org.springframework.security.oauth2.provider.approval;

import java.util.Collection;
import java.util.Date;
import java.util.HashSet;

import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.approval.Approval.ApprovalStatus;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

@Deprecated
public class TokenApprovalStore implements ApprovalStore {

    private TokenStore store;

    public void setTokenStore(TokenStore store) {
        this.store = store;
    }

    @Override
    public boolean addApprovals(Collection<Approval> approvals) {
        return true;
    }

    @Override
    public boolean revokeApprovals(Collection<Approval> approvals) {
        for (Approval approval : approvals) {
            Collection<OAuth2AccessToken> tokens = store.findTokensByClientIdAndUserName(approval.getClientId(), approval.getUserId());
            for (OAuth2AccessToken token : tokens) {
                OAuth2Authentication authentication = store.readAuthentication(token);
                if (authentication != null && approval.getClientId().equals(authentication.getOAuth2Request().getClientId())) {
                    store.removeAccessToken(token);
                }
            }
        }
        return true;
    }

    @Override
    public Collection<Approval> getApprovals(String userId, String clientId) {
        Collection<Approval> result = new HashSet<Approval>();
        Collection<OAuth2AccessToken> tokens = store.findTokensByClientIdAndUserName(clientId, userId);
        for (OAuth2AccessToken token : tokens) {
            OAuth2Authentication authentication = store.readAuthentication(token);
            if (authentication != null) {
                Date expiresAt = token.getExpiration();
                for (String scope : token.getScope()) {
                    result.add(new Approval(userId, clientId, scope, expiresAt, ApprovalStatus.APPROVED));
                }
            }
        }
        return result;
    }
}
